package br.com.buscapecas.validator;

import java.sql.SQLException;
import java.util.List;
import java.util.regex.Pattern;

import br.com.buscapecas.exception.BuscaPecasException;

/**
 * @author Maikon Rafael da Rocha
 * @since 10/09/2010 13:32:02
 */
public class EmailValidator extends Validator {

    /*
     * regex to validate email address noteworthy: (1) It allows usernames with
     * 1 or 2 alphanum characters, or 3+ chars can have -._ in the middle.
     * username may NOT start/end with -._ or any other non alphanumeric
     * character. (2) It allows heirarchical domain names (e.g.
     * me@really.big.com). Similar -._ placement rules there. (3) It allows 2-9
     * character alphabetic-only TLDs (that oughta cover museum and adnauseum
     * :&gt;). (4) No IP email addresses though -- I wouldn't Want to accept
     * that kind of address.
     */
    private static final Pattern emailPattern = Pattern.compile("^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$");

    /**
     * @param email
     * @param label
     * @param conn
     * @throws BuscaPecasException
     * @throws SQLException
     * @author Maikon Rafael da Rocha
     * @since 10/09/2010 13:54:39
     */
    public static void validateEmail(String email, String label) throws BuscaPecasException,
                                                                SQLException {
        boolean retorno = true;
        retorno = validateEmailPattern(email);
        if (!retorno)
            throw new BuscaPecasException(messagesResources.getString("invalidSingular", new Object[]{label}));
    }

    /**
     * @param messages
     * @param email
     * @param label
     * @param conn
     * @author Maikon Rafael da Rocha
     * @since 10/09/2010 13:54:36
     */
    public static void validateEmail(List<String> messages, String email, String label) {
        boolean retorno = true;
        retorno = validateEmailPattern(email);
        if (!retorno)
            messages.add(messagesResources.getString("invalidSingular", new Object[]{label}));
    }

    /**
     * @param conn
     * @param email
     * @param label
     * @param value
     * @param labelsRequired
     * @author Maikon Rafael da Rocha
     * @since 16/09/2010 07:52:33
     */
    public static boolean validateEmail(String email, String label, List<String> labelsRequired) {
        boolean retorno = true;
        retorno = validateEmailPattern(email);
        if (!retorno)
            labelsRequired.add(label);
        return retorno;
    }
    
    /**
     * 
     * @param email
     * @return
     * 
     * @author Maikon Rafael da Rocha
     * @since 08/12/2010 13:47:52
     */
    public static boolean validateEmailPattern(String email) {
        return emailPattern.matcher(email).matches();
    }

}